package com.ryan.route.listener;


import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ryan.exception.TravelException;
import com.ryan.route.entity.DestCategory;
import com.ryan.route.entity.vo.CategoryVo;
import com.ryan.route.service.DestCategoryService;

public class CategoryExcelListener extends AnalysisEventListener<CategoryVo> {

    //手动注入
    private DestCategoryService categoryService;

    public CategoryExcelListener() {
    }

    public CategoryExcelListener(DestCategoryService categoryService) {
        this.categoryService = categoryService;
    }

    //一行一行读取
    @Override
    public void invoke(CategoryVo categoryVo, AnalysisContext analysisContext) {
        //如果数据为空
        if(categoryVo == null){
            throw new TravelException(20001,"数据不存在");
        }

        //如果数据不为空，还需要判断分类是否重读
        //先判断一级分类
        String oneName = categoryVo.getOneCategory();
        DestCategory oneCategory = this.isExistOnCategory(categoryService, oneName);
        if (oneCategory == null){
            //如果为空则表示不重复，需要 添加
            oneCategory = new DestCategory();
            oneCategory.setParentId("0");
            oneCategory.setTitle(oneName);
            categoryService.save(oneCategory);
        }

        //判断二级分类
        String twoName = categoryVo.getTwoCategory();
        String pid1 = oneCategory.getId();
        DestCategory twoCategory = this.isExistTwoCategory(categoryService, twoName, pid1);
        if(twoCategory == null){
            twoCategory = new DestCategory();
            twoCategory.setParentId(pid1);
            twoCategory.setTitle(twoName);
            categoryService.save(twoCategory);
        }

    }

    private DestCategory isExistTwoCategory(DestCategoryService categoryService, String twoName, String pid1) {
        QueryWrapper<DestCategory> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", pid1);
        wrapper.eq("title", twoName);
        return categoryService.getOne(wrapper);
    }

    private DestCategory isExistOnCategory(DestCategoryService categoryService, String oneName) {
        QueryWrapper<DestCategory> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", "0");
        wrapper.eq("title", oneName);
        return categoryService.getOne(wrapper);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
